package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.activity.GonggaoDetailActivity.GongaoInfoAdapter;
import com.ycsj.goldmedalnewconcept.activity.HuodongActivity.MyBroadcastReceiver;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.GonggaoInfo;
import com.ycsj.goldmedalnewconcept.bean.GonggaoResponse;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;
import com.ycsj.goldmedalnewconcept.R;

// 公告
public class GonggaoActivity extends Activity implements OnRefreshListener,OnClickListener {

	private ImageView iv_back;
	private String role;
	private String account;
	private String type;
	private String id;
	private ListView lv_gonggao;
	private GongaoInfoAdapter mAdapter;
	private List<GonggaoInfo> gonggaolist;
	private List<String> imglist;
	private TextView tv_newgonggao;
	private TextView tv_empty;
	private PullToRefreshLayout refreshLayout;
	private IntentFilter intentFilter;
	private MyBroadcastReceiver myBroadcastReceiver;
	public static final String BROADCAST_ACTION1 ="refreshbroadcast1";
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_gonggao);
		role = SPUtil.getString(this, "role", "");
		account = SPUtil.getString(this, "account", "");
		if ("3".equals(role)) {
			type = "30";
		} else if ("2".equals(role)) {
			type = "31";
		} else if ("1".equals(role)) {
			type = "32";
		}

		gonggaolist = new ArrayList<GonggaoInfo>();

		initView();
		setOnListener();
		initData();
		registerCast();
	}

	
	/**
	 * 创建广播用于处理页面刷新
	 */
	private void registerCast() {
		 	intentFilter = new IntentFilter();
	        intentFilter.addAction("refreshbroadcast1");
	        myBroadcastReceiver = new MyBroadcastReceiver();
	        registerReceiver(myBroadcastReceiver, intentFilter);
		
	}

	
	 /**
     * 广播接受者
     */
    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播受重新刷新页面数据
            if (BROADCAST_ACTION1.equals(intent.getAction())) {
            	onRefresh();
            	Log.e("TEST", "RUN");
            }
        }
    }
	
	
	private void initView() {
		iv_back = (ImageView) findViewById(R.id.iv_back);
		lv_gonggao = (ListView) findViewById(R.id.lv_gonggao);
		tv_newgonggao = (TextView) findViewById(R.id.tv_newgonggao);
		tv_empty = (TextView) findViewById(R.id.tv_empty);
		refreshLayout = (PullToRefreshLayout)findViewById(R.id.refresh_view);
		refreshLayout.setOnRefreshListener(this);
		
		if ("3".equals(role)) {
			tv_newgonggao.setVisibility(tv_newgonggao.VISIBLE);
		}
	}

	private void initData() {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", type);
		builder.add("c", account);
		builder.add("role", role);
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			// http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=30&c=18672626702&role=3
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", json);
				GonggaoResponse fromJson = gson.fromJson(json,
						GonggaoResponse.class);

				if (fromJson != null) {
					if ("-1".equals(fromJson.state)
							|| "0".equals(fromJson.state)) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								tv_empty
								 .setVisibility(tv_empty.VISIBLE);
							}
						});
					} else if ("1".equals(fromJson.state)) {
						gonggaolist = fromJson.list;

						mAdapter = new GongaoInfoAdapter();
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								
								tv_empty
								 .setVisibility(tv_empty.GONE);
								refreshLayout
								.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
								lv_gonggao.setAdapter(mAdapter);
								lv_gonggao
										.setOnItemClickListener(new OnItemClickListener() {

											@Override
											public void onItemClick(
													AdapterView<?> parent,
													View view, int position,
													long id) {
												Intent intent = new Intent(
														GonggaoActivity.this,
														GonggaoDetailActivity.class);
												intent.putExtra("position",
														position);
												intent.putExtra("type", type);
												startActivity(intent);
											}
										});
								if ("3".equals(role)) {
									lv_gonggao.setOnItemLongClickListener(new OnItemLongClickListener() {

												@Override
												public boolean onItemLongClick(
														AdapterView<?> parent,
														View view,
														int position, long id) {
													String jsonid = "[{\"rowid\":\"" +gonggaolist.get(position).row_id+"\"}]";
													Log.e("test", jsonid);
													deldialog(jsonid);//删除条目的弹窗
													return true;
												}

												private BaseAnimatorSet bas_in;
												private BaseAnimatorSet bas_out;

												public void setBasIn(
														BaseAnimatorSet bas_in) {
													this.bas_in = bas_in;
												}

												public void setBasOut(
														BaseAnimatorSet bas_out) {
													this.bas_out = bas_out;
												}

												private void deldialog(String jsonid) {
													id = jsonid;
													final NormalDialog dialog = new NormalDialog(
															GonggaoActivity.this);
													dialog.content("确定删除此条公告？")
															.btnText("取消", "确认")//
															.style(NormalDialog.STYLE_TWO)//
															.titleTextSize(23)//
															.showAnim(bas_in)//
															.dismissAnim(
																	bas_out)//
															.show();
													dialog.setCanceledOnTouchOutside(false);
													dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

														@Override
														public void onBtnLeftClick() {
															dialog.dismiss();
														}
													});
													dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

														@Override
														public void onBtnRightClick() {
															//删除条目
															dialog.dismiss();
															
															OkHttpClient mOkHttpClient = new OkHttpClient();
															FormEncodingBuilder builder = new FormEncodingBuilder();
															builder.add("type", "29");
															builder.add("c", account);
															builder.add("role", role);
															builder.add("jsonid", id);
															Request request = new Request.Builder()
																	.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
																	.build();
															mOkHttpClient.newCall(request).enqueue(new Callback() {

																@Override
																public void onFailure(Request arg0, IOException arg1) {
																	runOnUiThread(new Runnable() {
																		@Override
																		public void run() {
																			Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
																					.show();
																		}
																	});
																}

																@Override
																public void onResponse(Response arg0) throws IOException {
																	// 解析Json数据，保存登录状态及身份信息

																	Gson gson = new Gson();
																	String json = arg0.body().string();
																	Log.e("test", json);
																	AttResponse fromJson = gson.fromJson(json,
																			AttResponse.class);

																	if (fromJson != null) {
																		if ("-1".equals(fromJson.state)
																				|| "0".equals(fromJson.state)) {
																			runOnUiThread(new Runnable() {
																				@Override
																				public void run() {
																					Toast.makeText(getBaseContext(), "删除失败，请检查网络连接是否正常", 0)
																					.show();
																				}
																			});
																		} else if ("1".equals(fromJson.state)) {
																			
																			runOnUiThread(new Runnable() {
																				@Override
																				public void run() {
																					initData();
																					Toast.makeText(getBaseContext(), "删除成功！", 0)
																					.show();
																					
																				}
																			});
																		}
																	}
																}
															});
															
															
														}
													});

												}
											});
								}

							}
						});
					}
				}
			}
		});
	}

	private void setOnListener() {
		iv_back.setOnClickListener(this);
		tv_newgonggao.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_newgonggao:
			
			Intent intent = new Intent(GonggaoActivity.this,GonggaoCreatActivity.class);
			startActivity(intent);
			break;
		}
	}

	class GongaoInfoAdapter extends BaseAdapter {

		public int getCount() {

			return gonggaolist.size();
		}

		public Object getItem(int position) {

			return null;
		}

		public long getItemId(int position) {

			return 0;
		}

		ViewHolder vh = null;

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(parent.getContext(),
						R.layout.item_gonggao, null);
				vh = new ViewHolder();

				vh.ll_imgs = (LinearLayout) convertView
						.findViewById(R.id.ll_imgs);
				vh.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
				vh.iv_img1 = (ImageView) convertView.findViewById(R.id.iv_img1);
				vh.iv_img2 = (ImageView) convertView.findViewById(R.id.iv_img2);
				vh.iv_img3 = (ImageView) convertView.findViewById(R.id.iv_img3);
				vh.tv_title = (TextView) convertView
						.findViewById(R.id.tv_title);
				vh.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
				vh.tv_content = (TextView) convertView
						.findViewById(R.id.tv_content);
				vh.iv_img.setVisibility(vh.iv_img.GONE);
				vh.ll_imgs.setVisibility(vh.ll_imgs.GONE);
				convertView.setTag(vh);
			} else {
				vh = (ViewHolder) convertView.getTag();
			}
			imglist = new ArrayList<String>();
			if (gonggaolist != null) {
				if (gonggaolist.get(position).user_picture1 != null
						&& !"".equals(gonggaolist.get(position).user_picture1)) {
					imglist.add(gonggaolist.get(position).user_picture1);
				}
				if (gonggaolist.get(position).user_picture2 != null
						&& !"".equals(gonggaolist.get(position).user_picture2)) {
					imglist.add(gonggaolist.get(position).user_picture2);
				}
				if (gonggaolist.get(position).user_picture3 != null
						&& !"".equals(gonggaolist.get(position).user_picture3)) {
					imglist.add(gonggaolist.get(position).user_picture3);
				}
			}

			if (imglist.size() == 0) {
				vh.ll_imgs.setVisibility(vh.ll_imgs.GONE);
				vh.iv_img.setVisibility(vh.iv_img.GONE);
			} else if (imglist.size() == 1) {
				vh.ll_imgs.setVisibility(vh.ll_imgs.GONE);
				vh.iv_img.setVisibility(vh.iv_img.VISIBLE);
				Picasso.with(GonggaoActivity.this)
						.load(gonggaolist.get(position).user_picture1)
						.into(vh.iv_img);
			} else if (imglist.size() == 2) {
				vh.ll_imgs.setVisibility(vh.ll_imgs.VISIBLE);
				vh.iv_img.setVisibility(vh.iv_img.GONE);

				Picasso.with(GonggaoActivity.this)
						.load(gonggaolist.get(position).user_picture1)
						.into(vh.iv_img1);

				Picasso.with(GonggaoActivity.this)
						.load(gonggaolist.get(position).user_picture2)
						.into(vh.iv_img2);
			} else if (imglist.size() == 3) {
				vh.ll_imgs.setVisibility(vh.ll_imgs.VISIBLE);
				vh.iv_img.setVisibility(vh.iv_img.GONE);

				Picasso.with(GonggaoActivity.this)
						.load(gonggaolist.get(position).user_picture1)
						.into(vh.iv_img1);

				Picasso.with(GonggaoActivity.this)
						.load(gonggaolist.get(position).user_picture2)
						.into(vh.iv_img2);

				Picasso.with(GonggaoActivity.this)
						.load(gonggaolist.get(position).user_picture3)
						.into(vh.iv_img3);

			}


			vh.tv_title.setText(gonggaolist.get(position).tag);
			vh.tv_time.setText(gonggaolist.get(position).update_date);
			vh.tv_content.setText(gonggaolist.get(position).content);

			return convertView;
		}

		class ViewHolder {
			private TextView tv_title;
			private ImageView iv_img;
			private ImageView iv_img1;
			private ImageView iv_img2;
			private ImageView iv_img3;
			private TextView tv_time;
			private TextView tv_content;
			private LinearLayout ll_imgs;

		}
	}

	@Override
	public void onRefresh() {
		// 下拉刷新操作
		new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				initData();
			}
		}, 500);
	}
}







